'''
1、有文件“分数.txt”，求平均分。文件中的部分分数的格式有误，
不允许修改文件，用“异常处理”计算。(文件名：py0233.py)
'''
import re

f = open("分数.txt", "r")
score = 0
grades = []
grades_ = []
str_grades = " ".join(f.readlines())
print(str_grades)
grades = re.split(',|-|\n|\r| ', str_grades)
print(grades)
f.close()
aver, sum_ = 0.0, 0
for i in range(len(grades)):
    try:
        score = int(grades[i])
    except:
        pass
    else:
        grades_.append(score)
        sum_ += score
aver = sum_ / len(grades_)
print("从分数.txt文件中读取的所有分数如下:")
print(grades_)
print("所有分数的平均值为:{:.3f}".format(aver))
"""
while True:
    str = f.readline()
    if str == "":     # 空行也有换行符会被识别出来
        break
    else:
        try:
            score = (int(str))
        except:
            pass
        else:
            grades.append(score)

print("从分数.txt文件中读取的所有分数如下:")
print(grades)


aver, sum_ = 0.0, 0
for i in range(len(grades)):
    sum_ += grades[i]
f.close()
aver = sum_ / len(grades)
print("所有分数的平均值为:{:.3f}".format(aver))
"""